unit MainUnit;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, {db, sqlite3ds, sqldb, sqlite3conn,} LResources,
  Forms, Controls, Graphics, Dialogs, StdCtrls, Menus, ComCtrls, ExtCtrls,
  DbCtrls, ItemsUnit, AboutUnit, MyConnector, MyTypes, MyDatabase, ShowDB;

type

  { TMyThread }
 {
  TMyThread = class(TThread)
  private
    fStatusText,RootItem: string;
    procedure ShowStatus;
    procedure UpdateGroupTree;
  protected
    procedure Execute; override;
  public
    constructor Create(CreateSuspended: boolean);
  end;     }

  { TMsgListThread}
{  TMsgListThread = class(TThread)
  private
    fStatusText, GroupTreeSelectedText: string;
    Lock:boolean;
    procedure ShowStatus;
    procedure AddListMesgItems;
    procedure GroupTreeLock;
  protected
    procedure Execute; override;
  public
    constructor Create(CreateSuspended: boolean; SendText:string);
  end;     }


  { TMainForm }

  TMainForm = class(TForm)
    btnConnect: TButton;
    btnLogout: TButton;
    btnAddServer: TButton;
    lcbServer: TDBLookupComboBox;
   { dsTable: TDatasource;}
    FontDialog1: TFontDialog;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    ListMesg: TListBox;
    MainMenu1: TMainMenu;
    itmParameters: TMenuItem;
    itmAbout: TMenuItem;
    itmFont: TMenuItem;
    MenuItem1: TMenuItem;
    MessageMemo: TMemo;
    dbOpen: TOpenDialog;
    ProcessMemo: TMemo;
    PortEdit: TEdit;
    HostEdit: TEdit;
    LoginEdit: TEdit;
    PasswordEdit: TEdit;
    GroupTree: TTreeView;
{    TServer: TSqlite3Dataset;}
    procedure btnAddServerClick(Sender: TObject);
    procedure btnConnectClick(Sender: TObject);
    procedure btnLogoutClick(Sender: TObject);
    procedure GroupTreeClick(Sender: TObject);
    procedure lcbServerChange(Sender: TObject);
    procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure itmAboutClick(Sender: TObject);
    procedure itmFontClick(Sender: TObject);
    procedure ListMesgClick(Sender: TObject);
    procedure MenuItem1Click(Sender: TObject);
  private
  public
  end;

var
  MainForm: TMainForm;
  {MyThread : TMyThread;
  MsgListThread : TMsgListThread;}
  i,j:integer;
  ListData:TextFile;

  connector:TConnector;
  groups:TGroupList;
  group:TGroup;
  messages:TMessageList;
  server:TNNTPServer;

implementation

{Functions}



{ TMainForm }

//Создание формы
procedure TMainForm.FormCreate(Sender: TObject);
begin
{  Если файл с БД не найден, его открывает пользователь}
{TdbServer.check;}
{  If not(FileExists(TServer.FileName)) then
  begin
    If dbOpen.Execute then
    TServer.FileName:=dbOpen.FileName;
  end;
  TServer.Active:=True;}
{чтобы при открытии окна было чтонить в
lcbServer??? походу никак}
  {lcbServer.ListFieldIndex:=1;}
  ProcessMemo.Text:='';
  MessageMemo.Text:='';
  //PasswordEdit and Login initialization
  PasswordEdit.Text:='';
  LoginEdit.Text:='';
  PortEdit.Text:='119';
  HostEdit.Text:='ddt.demos.su';
end;

//Кнопка "Cоединить"
procedure TMainForm.btnConnectClick(Sender: TObject);
var groupCount: integer;
begin
  {btnConnect.Enabled:=False;
  btnLogout.Enabled:=True;}
  server:= TNNTPServer.Create();
  server.name :='ddt.demos.su';
  server.port :='119';
  server.userName := '';
  server.password :='';
  ProcessMemo.Append(server.name);

  connector:=TConnector.Create ;
  connector.ConnectToServer(server);

 { //MyThread
  If MyThread<>nil then
  MyThread.Terminate;

  MyThread := TMyThread.Create(True); // With the True parameter it doesn't start automatically
  if Assigned(MyThread.FatalException) then
  raise MyThread.FatalException;
  MyThread.Resume;}

  {formdddddd.GetGroups(groups1, groupCount);}

  connector.GetGroups(groups);
{  dbProvider.SaveGroupList(server.Id, groups1);
  dbProvider.GetGroupListByServerId(server.Id, groups1);
 }
  For i:=1 to (Length(groups)-1) do
  begin
     MainForm.GroupTree.Items.Add (nil,groups[i].Name) ;
  end;



end;  {proc}


//Кнопка "add server"
procedure TMainForm.btnAddServerClick(Sender: TObject);
var dbServer:TdbServer;
begin
 { TServer.AppendRecord([Nil, HostEdit.Text, StrToInt(PortEdit.Text), LoginEdit.Text, PasswordEdit.Text]);
  TServer.ApplyUpdates;
  lcbServer.Text:=HostEdit.Text;}


  server:= TNNTPServer.Create();
  server.name :=HostEdit.Text ;
  server.port :=PortEdit.Text;
  server.userName := LoginEdit.Text;
  server.password :=PasswordEdit.Text;


  dbServer:=TdbServer.Create;
  dbServer.SetTo(Server);
end;

//Кнопка "logout"
procedure TMainForm.btnLogoutClick(Sender: TObject);
begin
  GroupTree.Items.Clear;
  MessageMemo.Clear;
  ListMesg.Clear;
{  myNNTP.Logout;

  myNNTP.Free;
  ProcessMemo.Append('Команда: ?Logout?');
 }
  connector.Disconnect;
  btnLogout.Enabled:=False;
  btnConnect.Enabled:=True;
end;

procedure TMainForm.GroupTreeClick(Sender: TObject);
var i:integer; messageCount:Integer;
begin
{  ListMesg.Clear;
    MessageMemo.Text:='';

    If MsgListThread <> nil then
    MsgListThread.Terminate;

    MsgListThread := TMsgListThread.Create(True, GroupTree.Selected.Text);
       // With the True parameter it doesn't start automatically
    if Assigned(MsgListThread.FatalException) then
      raise MsgListThread.FatalException;
    MsgListThread.Resume;
             }

    connector.GetGroups(groups);
    For i:=0 to (Length(groups)-1) do
    begin
      if (groups[i].Name = GroupTree.Selected.Text) then
      begin
        group:=groups[i];
        ProcessMemo.Append(GroupTree.Selected.Text);
      end;
    end;

    connector.GetMessages(group, messages);
    For i:=0 to (Length(messages)-1) do
    begin
      ListMesg.Items.Add(messages[i].Head);
    end;
end;

//Выбор сервера из списка
procedure TMainForm.lcbServerChange(Sender: TObject);
begin
  HostEdit.Text:=lcbServer.Text;
{  TServer. }
  {with TServer do
  begin
{    Open;}
    First;
    while not Eof do
    begin
      If FieldByName('servername').AsString=lcbServer.Text then
      begin
        PortEdit.Text:=FieldByName('port').AsString;
        LoginEdit.Text:=FieldByName('username').AsString;
        PasswordEdit.Text:=FieldByName('password').AsString;
      end;
      Next;
    end;
  end;}
end;

//Клик по списку сообщений
procedure TMainForm.ListMesgClick(Sender: TObject);
begin
 {Дописать чтобы впустую не срабатывало и может ещё где...}
 { MyNNTP.GetArticle( copy(ListMesg.GetSelectedText,1,pos(' ', ListMesg.GetSelectedText)-1) );
  Memo2.Text:=
   Memo2.Text+
    MyNNTP.Data.Text + 'Body:' + Crlf;}
{  MyNNTP.GetBody( copy(ListMesg.GetSelectedText,1,pos(' ', ListMesg.GetSelectedText)-1) );
  MessageMemo.Text:=MyNNTP.Data.Text;
  ProcessMemo.Append('Сообщение: '+ copy(ListMesg.GetSelectedText,1,pos(' ', ListMesg.GetSelectedText)-1) );}
end;

//Показать БД
procedure TMainForm.MenuItem1Click(Sender: TObject);
begin
    Application.CreateForm(TForm1, Form1);
    Form1.ShowModal;
    Form1.Free; {освобождаем ресурсы служебного окна}
end;

//Меню "О программе"
procedure TMainForm.itmAboutClick(Sender: TObject);
begin
  {about}
  Application.CreateForm(TAboutForm, AboutForm);
  AboutForm.ShowModal;
  AboutForm.Free;
end;

//Меню "Параметры -> Шрифт"
procedure TMainForm.itmFontClick(Sender: TObject);
begin
  FontDialog1.Font:=MessageMemo.Font;
  If FontDialog1.Execute then MessageMemo.Font:= FontDialog1.Font;
end;

//Закрытие формы
procedure TMainForm.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
 { If (MyThread<>nil) then
    MyThread.Terminate;
  If (MsgListThread<>nil) then
    MsgListThread.Terminate;
  If (myNNTP<>nil) then
    btnLogout.Click;}
end;

{ TMyThread }
{
procedure TMyThread.ShowStatus;
begin
  MainForm.ProcessMemo.Append(fStatusText);
end;

procedure TMyThread.UpdateGroupTree;
begin
   MainForm.GroupTree.Items.Add(nil,RootItem) ;
end;

procedure TMyThread.Execute;
begin
  {=== LOGIN ===}

  //HOST+PORT
  fStatusText:='New connection detected';
  Synchronize(@Showstatus);

  myNNTP.TargetHost:=MainForm.HostEdit.Text ;
  myNNTP.TargetPort:=MainForm.PortEdit.Text ;

  fStatusText:='Статус: Соединяюсь с '+myNNTP.TargetHost+':'+myNNTP.TargetPort;;
  Synchronize(@Showstatus);

  //LOGIN+PasswordEdit
  If not(MainForm.LoginEdit.Text  = '') then
    begin
      myNNTP.UserName:=MainForm.LoginEdit.Text;
      {ProcessMemo.Text:=ProcessMemo.Text+'User: '+myNNTP.UserName;}
      If not(MainForm.PasswordEdit.Text = '' ) then
        myNNTP.Password:=MainForm.PasswordEdit.Text;
    end;

  fStatusText:='Команда: ?Login?';
  Synchronize(@Showstatus);
  myNNTP.Login;

  fStatusText:='Ответ: '+inttostr(myNNTP.ResultCode)+' '+myNNTP.ResultString;
  Synchronize(@Showstatus);

  {=== LIST ===}

  // list
  fStatusText:='Команда: ?ListGroups?';
  Synchronize(@Showstatus);
  myNNTP.ListGroups;
  fStatusText:='Ответ: '+inttostr(myNNTP.ResultCode)+' '+myNNTP.ResultString;
  Synchronize(@Showstatus);

  {Добавить вывод в БД}
  For i:=0 to myNNTP.Data.Count-1 do
  begin
     If ( ( LastArticleNumber(myNNTP.Data.Strings[i]) - FirstArticleNumber(myNNTP.Data.Strings[i]) ) > 0 )
     {т.е., если есть сообщения в группе}
     then
     Begin
       RootItem:=MinimalOfDataGroupString(myNNTP.Data.Strings[i])  ;
       Synchronize(@UpdateGroupTree);
       {Добавили в список групп в главном окне}
     end;
  end;
    fStatusText:='Запись в GroupList... ok';
    Synchronize(@Showstatus);

    MyThread.Terminate;
end;

constructor TMyThread.Create(CreateSuspended: boolean);
begin
  FreeOnTerminate := True;
  inherited Create(CreateSuspended);
end;

 { TMsgListThread}

procedure TMsgListThread.ShowStatus;
begin
  MainForm.ProcessMemo.Append(fStatusText);
end;

procedure TMsgListThread.AddListMesgItems;
begin
  MainForm.ListMesg.Items.Add(myNNTP.ResultString);
end;

procedure TMsgListThread.GroupTreeLock;
begin
  MainForm.GroupTree.Enabled:=Not(Lock);
end;

procedure TMsgListThread.Execute;
begin
    Lock:=True;
    Synchronize(@GroupTreeLock);
    myNNTP.SelectGroup(GroupTreeSelectedText);
      {Исправить, используя БД?????}
{    StringsOfAllThisItems:=TStringList.Create;
    StringsOfAllThisItems.LoadFromFile('ListData');

    For i:=0 to StringsOfAllThisItems.Count-1 do {0 to ...-1????}
    begin
      if (copy(GroupTreeSelectedText,1,length(GroupTreeSelectedText)) =
       copy(StringsOfAllThisItems.Strings[i],1,length(GroupTreeSelectedText)) )
      then
      begin
        for j:=FirstArticleNumber(StringsOfAllThisItems.Strings[i]) to
         LastArticleNumber(StringsOfAllThisItems.Strings[i]) do
        begin
            myNNTP.GetStat(IntToStr(j));
            Synchronize(@AddListMesgItems);
        end; {for}
      end; {if}
    end; {for}

    fStatusText:='Запись в ListMesg... ok'+GroupTreeSelectedText;
    Synchronize(@Showstatus);

    StringsOfAllThisItems.Free;       }

    Lock:=False;
    Synchronize(@GroupTreeLock);
    MyThread.Terminate;
end;

constructor TMsgListThread.Create(CreateSuspended: boolean; SendText:string);
begin
  FreeOnTerminate := True;
  inherited Create(CreateSuspended);
  GroupTreeSelectedText:=SendText;
end;                  }

initialization
  {$I mainunit.lrs}
end.

